unit ec_selectitem;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons,
  StdCtrls, EditBtn, ec_base;

type

  { TECSelectItemFrame }

  TECSelectItemFrame = class(TECBaseFrame)
    ItemTypeComboBox: TComboBox;
    VariableEditButton: TEditButton;
    VariableLabel: TLabel;
    ItemTypeLabel: TLabel;
    procedure VariableEditButtonButtonClick(Sender: TObject);
    procedure VariableEditButtonKeyPress(Sender: TObject; var Key: char);
  private
    VariableId: Integer;

    procedure InitialSetup;
    procedure UpdateVariableId;
  public
    procedure InitExisting; override;
    procedure InitNew; override;
    procedure MakeResultingCommand; override;
  end;

var
  ECSelectItemFrame: TECSelectItemFrame;

implementation

uses
  comboboxhelper, fpjson, namedindexselection, constants;

{$R *.lfm}

{ TECSelectItemFrame }

procedure TECSelectItemFrame.VariableEditButtonButtonClick(Sender: TObject);
begin
  VariableId := NamedIndexSelectionForm.SelectVariable(VariableId, Db);
  UpdateVariableId;
end;

procedure TECSelectItemFrame.VariableEditButtonKeyPress(Sender: TObject;
  var Key: char);
begin
  Key := #0;
  VariableEditButtonButtonClick(Sender);
end;

procedure TECSelectItemFrame.InitialSetup;
begin
  FillItemTypeCombobox(ItemTypeComboBox);
end;

procedure TECSelectItemFrame.UpdateVariableId;
begin
  VariableEditButton.Text := Db.GetVariableName(VariableId);
end;

procedure TECSelectItemFrame.InitExisting;
var
  Params: TJSONArray;
begin
  InitialSetup;

  Params := GetFirstParams;

  if Params = nil then
     Exit;

  if (Params.Count >= 1) and (Params[0].JSONType = jtNumber) then
    VariableId := Params.Integers[0]
  else
    VariableId := 1;
  UpdateVariableId;

  if (Params.Count >= 2) and (Params[1].JSONType = jtNumber) then
    ItemTypeComboBox.ItemIndex := Params.Integers[1]
end;

procedure TECSelectItemFrame.InitNew;
begin
  InitialSetup;

  VariableId := 1;
  UpdateVariableId;

  ItemTypeComboBox.ItemIndex := 0;
end;

procedure TECSelectItemFrame.MakeResultingCommand;
begin
  ResultingCommand := TJSONArray.Create([
    TJSONObject.Create([
      'code', SELECT_ITEM_EC_CODE,
      'indent', Indent,
      'parameters', TJSONArray.Create([
        VariableId,
        ItemTypeComboBox.ItemIndex
      ])
    ])
  ]);
end;

end.

